from django.db import models
from config_app.models import ProjectModel
from utils.model import BaseModel, Chioce


def _default_dict():
    return {}


def _default_list():
    return []


class PubParamModel(BaseModel):
    verbose_name = '接口测试公共参数'

    name = models.CharField(max_length=50, unique=True)
    value = models.TextField()
    project = models.ForeignKey(to=ProjectModel, related_name='+', null=True, on_delete=models.SET_NULL)

    class Meta:
        db_table = 'interface_pub_param'


class CaseModel(BaseModel):
    verbose_name = '接口测试用例'

    project = models.ForeignKey(to=ProjectModel, related_name='+', null=True, on_delete=models.SET_NULL)
    redirect = models.BooleanField(default=False)

    name = models.CharField(max_length=100, unique=True)
    desc = models.TextField()
    server = models.CharField(max_length=100, null=True, default=None)
    protocol = models.CharField(max_length=10)
    url = models.CharField(max_length=500)
    method = models.CharField(max_length=10)

    headers = models.JSONField(default=_default_list)

    # 参数
    param_data = models.JSONField(default=_default_list)
    form_data = models.JSONField(default=_default_list)
    json_data = models.JSONField(default=_default_list)

    # 断言
    assert_status = models.JSONField(default=_default_list)
    assert_json = models.JSONField(default=_default_list)
    assert_headers = models.JSONField(default=_default_list)

    class Meta:
        db_table = 'interface_case'
        ordering = ['id']


class CaseSetModel(BaseModel):
    verbose_name = '接口测试用例集'

    name = models.CharField(max_length=50, unique=True)
    project = models.ForeignKey(to=ProjectModel, related_name='+', null=True, on_delete=models.SET_NULL)
    execute_num = models.IntegerField(default=0)
    execute_fin_time = models.DateTimeField(null=True)

    class Meta:
        db_table = 'interface_case_set'


class CaseSetDetailModel(BaseModel):
    verbose_name = '接口测试用例、用例集关系'

    set = models.ForeignKey(to=CaseSetModel, related_name='to_set', null=True, on_delete=models.SET_NULL)
    case = models.ForeignKey(to=CaseModel, related_name='to_case', null=True, on_delete=models.SET_NULL)

    class Meta:
        db_table = 'interface_case_set_relation'
        unique_together = ('set', 'case')


class CaseResultModel(BaseModel):
    verbose_name = '接口测试报告'

    set = models.ForeignKey(to=CaseSetModel, null=True, related_name='+', on_delete=models.SET_NULL)
    status = models.IntegerField()
    case_num = models.IntegerField(null=True)
    success_num = models.IntegerField(null=True)
    fail_num = models.IntegerField(null=True)
    time_cost = models.FloatField(null=True)
    result = models.TextField(null=True)

    class Status(Chioce):
        dict = {
            0: '正在执行',
            1: '执行完成',
            2: '执行失败',
        }

    class Meta:
        db_table = 'interface_result'
        ordering = ['id']
